<?php
// +----------------------------------------------------------------------
// | RXThinkCMF_EVTP5.1_PRO前后端分离旗舰版框架 [ RXThinkCMF ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2021 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.rxthink.cn
// +----------------------------------------------------------------------
// | 作者: ZhangXuanNeng <rxthinkcmf@163.com>
// +----------------------------------------------------------------------
// | 免责声明:
// | 本软件框架禁止任何单位和个人用于任何违法、侵害他人合法利益等恶意的行为，禁止用于任何违
// | 反我国法律法规的一切平台研发，任何单位和个人使用本软件框架用于产品研发而产生的任何意外
// | 、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、附带
// | 或衍生的损失等)，本团队不承担任何法律责任。本软件框架只能用于公司和个人内部的法律所允
// | 许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\service;

use app\admin\model\BoxGmEcs;
use app\admin\model\BoxGmEs;
use app\admin\model\BoxGmRedis;
use app\admin\model\BoxGmSerOrder;
use think\Db;
use think\Exception;

/**
 * 渠道管理-服务类
 * @author steven
 * @since: 2024/01/22
 * Class ChannelService
 * @package app\admin\service
 */
class ChannelSerOrderService extends BaseService
{
    /**
     * 构造函数
     * LevelService constructor.
     */
    public function __construct()
    {
        $this->model = new BoxGmSerOrder();
    }

    /**
     * 获取数据列表
     * @return array
     * @since 2023/08/07
     * @author steven
     */
    public function getList(): array
    {
        $param = request()->param();
        // 查询条件
        $map = [];
        $id  = isset($param['id']) ? trim($param['id']) : '';
        if ($id) {
            $map[] = ['a.id', '=', $id];
        }
        // 渠道名称
        $name = isset($param['order_num']) ? trim($param['order_num']) : '';
        if ($name) {
            $map[] = ['a.order_num', 'like', "%{$name}%"];
        }
        // 有效标识
        $status = isset($param['status']) ? trim($param['status']) : '';
        if ($status != '') {
            $map[] = ['a.status', '=', intval($status)];
        }

        $list = $this->model->alias('a')
            ->field('a.*,c.nickname')
            ->leftJoin('user_channel c', 'a.channel_user_id = c.id')
            ->where($map)
            ->order('a.id', 'desc')
            ->paginate($param['limit'])
            ->toArray();
        $arr  = $list['data'] ?? [];
        //返回结果
        return array(
            "msg"   => '操作成功',
            "code"  => 0,
            "data"  => $arr,
            "count" => $list['total'],
        );
    }

    public function edit()
    {
        $param = request()->param();
        if($param['ser_custom'] == 1){
            $ser_data = json_decode($param['ser_data'],true);
            switch ($param['ser_type']){
                case 1:
                    $ser_data['ecs_price'] = $param['price'];
                    break;
                case 2:
                    $ser_data['redis_price'] = $param['price'];
                    break;
                case 3:
                    $ser_data['es_price'] = $param['price'];
                    break;
            }
            if (isset($ser_data) && !empty($ser_data)) {
                $param['ser_data']  = json_encode($ser_data,true);
            }
        }

        return parent::newEdit($param, false, true); // TODO: Change the autogenerated stub
    }

    /**
     * Desc : 数据资产
     * User : Steven
     * Date : 2024-01-25 21:56
     * @return array
     */
    public function assets(): array
    {
        $params = request()->param();
        if (empty($params['ser_type'])) {
            return ['code' => -1, 'msg' => '添加失败'];
        }
        $baseData = [
            'channel_user_id' => $params['channel_user_id'],
            'order_id'        => $params['id'],
            'is_custom'       => $params['ser_custom'],
        ];
        Db::startTrans();
        try {
            switch ($params['ser_type']) {
                case 1:
                    $insertData = [
                        'ecs_name' => 'ecs_' . generateCode(12),
                        'ecs_ip'   => $params['ecs_ip'],
                        'ecs_pwd'  => $params['ecs_pwd'],
                    ];
                    $insertData = array_merge($insertData, $baseData);
                    $ecsModel   = new BoxGmEcs();
                    $id         = $ecsModel->field('id')->where('order_id', $params['id'])->find();
                    if ($id['id']) {
                        $insertId = $ecsModel->where('id', $id['id'])->update($insertData);
                    } else {
                        $insertId = $ecsModel->insertGetId($insertData);
                    }
                    if (empty($insertId)) {
                        throw new Exception('ECS初始化失败!');
                    }
                    break;
                case 2:
                    $insertData = [
                        'redis_name' => 'redis_' . generateCode(12),
                        'redis_ip'   => $params['redis_ip'],
                        'redis_pwd'  => $params['redis_pwd'],
                    ];
                    $insertData = array_merge($insertData, $baseData);
                    $redisModel = new BoxGmRedis();
                    $id         = $redisModel->field('id')->where('order_id', $params['id'])->find();
                    if ($id['id']) {
                        $insertId = $redisModel->where('id', $id['id'])->update($insertData);
                    } else {
                        $insertId = $redisModel->insertGetId($insertData);
                    }
                    if (empty($insertId)) {
                        throw new Exception('Redis初始化失败!');
                    }
                    break;
                case 3:
                    $insertData = [
                        'es_name' => 'es_' . generateCode(12),
                        'es_ip'   => $params['es_ip'],
                        'es_pwd'  => $params['es_pwd'],
                    ];
                    $insertData = array_merge($insertData, $baseData);
                    $esModel    = new BoxGmEs();
                    $id         = $esModel->field('id')->where('order_id', $params['id'])->find();
                    if ($id) {
                        $insertId = $esModel->where('id', $id['id'])->update($insertData);
                    } else {
                        $insertId = $esModel->insertGetId($insertData);
                    }
                    if (empty($insertId)) {
                        throw new Exception('ES初始化失败!');
                    }
                    break;
            }
            $updateData = ['status' => 4, 'delivery_time' => date('Y-m-d H:i:s')];
            $this->model->where(['id' => $params['id']])->update($updateData);
            Db::commit();
            return ['code' => 0, 'msg' => '添加成功'];
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


}